<template>
  <div class="component-upload-image">
    <a-upload
      ref="refUploadImage"
      multiple
      list-type="picture-card"
      image-preview
      :action="actionURL"
      :headers="headers"
      :limit="limit"
      :file-list="fileList"
      @before-upload="handleBeforeUpload"
      @success="handleUploadSuccess"
      @error="handleUploadError"
      @exceed-limit="handleExceedLimit"
      @before-remove="handleDelete"
    >
    </a-upload>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineEmits, getCurrentInstance } from "vue";
import { Modal, Message } from "@arco-design/web-vue";
import { getToken } from "@/utils/auth";

const refUploadImage = ref(null)

const props = defineProps({
  modelValue: [String, Object, Array],
  // 上传 code ADVERT_IMAGE_UPLOAD，RICH_IMAGE_UPLOAD，GUIDE_IMAGE_UPLOAD，FAQ_DOCUMENT_WORD_UPLOAD
  // code: {
  //   type: String,
  //   require: true
  // },
  // 图片数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"]
  },
  // 是否显示提示
  // isShowTip: {
  //   type: Boolean,
  //   default: true
  // },
  // 图片推荐尺寸
  imgSize: {
    type: String,
    default: ""
  }
});

// const tips = computed(() => {
//   const tipsText = ['请上传']
//     if(props.fileSize) {
//       tipsText.push(`大小不超过${props.fileSize}MB`)
//     }
//   if(props.fileSize) {
//     tipsText.push(`格式为${props.fileType.join("/")}MB的文件`)
//   }
//   if(props.fileSize) {
//     tipsText.push(`推荐尺寸${props.imgSize}。`)
//   }
//   return tipsText.join('，')
// })

// const { proxy } = getCurrentInstance();

interface EmitEvent {
  (e: "update:modelValue", params: string): void;
}

const emit = defineEmits<EmitEvent>();

const number = ref(0);
const uploadList = ref([]);


// 上传的图片服务器地址
const BASE_URL = import.meta.env.VITE_API_BASE_URL;
const actionURL = ref(`${BASE_URL}/admin/upload/multiple`);

// const actionURL = computed(() => {
//   if (props.code) {
//     return `${baseUrl}/common/upload/${props.code}`;
//   }
//   return `${baseUrl}/common/upload`;
// });

const headers = ref({ Authorization: `Bearer ${getToken()}` });
const fileList = ref([]);
// const showTip = computed(
//   () => props.isShowTip && (props.fileType || props.fileSize)
// );

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(",");
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === "string") {
          // 判断是否已经带有https？
          if (/^(https?:|http:|data:)/.test(item)) {
            item = { name: item, url: item };
          } else {
            item = { name: item, url: item };
            // item = { name: baseUrl + item, url: baseUrl + item };
          }
        }
        return item;
      });
    } else {
      fileList.value = [];
    }
  },
  { deep: true, immediate: true }
);

// 上传前loading加载
// eslint-disable-next-line consistent-return
function handleBeforeUpload(file) {
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    Message.error(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      Message.error(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  console.log(file)

  // proxy.$modal.loading("正在上传图片，请稍候...");
  // eslint-disable-next-line no-plusplus
  number.value++;
  return true
}

// 文件个数超出
function handleExceedLimit() {
  Message.error(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 删除图片
function handleDelete(file) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: "删除图片",
      content: `确认删除 ${file.name}`,
      onOk: () => {
        const findex = fileList.value.map((f) => f.name).indexOf(file.name);
        if (findex > -1 && uploadList.value.length === number.value) {
          fileList.value.splice(findex, 1);
          // eslint-disable-next-line no-use-before-define
          emit("update:modelValue", listToString(fileList.value));
          // return false;
        }
        resolve(true);
      },
      // eslint-disable-next-line prefer-promise-reject-errors
      onCancel: () => reject("cancel")
    });
  });
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    // eslint-disable-next-line no-use-before-define
    emit("update:modelValue", listToString(fileList.value));
    // proxy.$modal.closeLoading();
  }
}

// 上传成功回调
function handleUploadSuccess(fileItem) {
  console.log({ fileItem })
  uploadList.value.push({ name: fileItem.name, url: fileItem.url });
  uploadedSuccessfully();
  // if (res.code === 200 && res.data) {
  //   // 旧数据
  //   // fileName:"/profile/upload/2023/06/29/0000_20230629103755A001.jpg"
  //   // newFileName:"0000_20230629103755A001.jpg"
  //   // originalFilename: "0000.jpg"
  //   // url:"https://cpportal-admin.qknode.com/profile/upload/2023/06/29/0000_20230629103755A001.jpg"
  //   // 新数据
  //   // name:"e7c95821d95142c6bdef9abf7eaa9afe.jpg"
  //   // objectName:"public/upload/advert/image20230629/e7c95821d95142c6bdef9abf7eaa9afe.jpg"
  //   // url: "https://cp-portal.obs.cn-south-1.myhuaweicloud.com:443/public%2Fupload%2Frich%2Fimage20230629%2F1ba1b9a90ac8487eb91ce6228e6a5cbc.jpg"
  //
  // } else {
  //   // eslint-disable-next-line no-plusplus
  //   number.value--;
  //   // proxy.$modal.closeLoading();
  //   // proxy.$modal.msgError(res.msg);
  //   // refUploadImage.value.handleRemove(file);
  //   uploadedSuccessfully();
  // }
}

// 上传失败
function handleUploadError() {
  // proxy.$modal.msgError("上传图片失败");
  // proxy.$modal.closeLoading();
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  // eslint-disable-next-line no-restricted-syntax
  for (const i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url + separator;
    }
  }
  // eslint-disable-next-line eqeqeq
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
</script>

<style scoped lang="less">
</style>
